package com.yubb.platform.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.annotation.PostConstruct;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yubb.common.core.domain.platform.dto.SysDictTypeDTO;
import com.yubb.common.core.domain.platform.vo.SysDictDataVO;
import com.yubb.common.core.domain.platform.vo.SysDictTypeVO;
import com.yubb.common.utils.bean.DozerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yubb.common.constant.UserConstants;
import com.yubb.common.core.domain.Ztree;
import com.yubb.common.core.domain.platform.SysDictData;
import com.yubb.common.core.domain.platform.SysDictType;
import com.yubb.common.core.text.Convert;
import com.yubb.common.exception.BusinessException;
import com.yubb.common.utils.DictUtils;
import com.yubb.common.utils.StringUtils;
import com.yubb.platform.mapper.SysDictDataMapper;
import com.yubb.platform.mapper.SysDictTypeMapper;
import com.yubb.platform.service.ISysDictTypeService;

/**
 *@Description 字典 业务层处理
 *@Author zhushuyong
 *@Date 2021/6/17 14:19
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType>
        implements ISysDictTypeService {
    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        List<SysDictType> dictTypeList = dictTypeMapper.selectList(null);
        for (SysDictType dictType : dictTypeList)
        {
            List<SysDictDataVO> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
            DictUtils.setDictCache(dictType.getDictType(), dictDatas);
        }
    }

    /**
     * 根据条件分页查询字典类型
     * 
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictTypeVO> selectDictTypeList(SysDictTypeDTO dictType)
    {
        return dictTypeMapper.selectDictTypeList(dictType);
    }

    /**
     * 根据所有字典类型
     * 
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictTypeVO> selectDictTypeAll()
    {
        return BeanUtil.copyToList(dictTypeMapper.selectList(null), SysDictTypeVO.class);
    }

    /**
     * 根据字典类型查询字典数据
     * 
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictDataVO> selectDictDataByType(String dictType)
    {
        List<SysDictDataVO> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = dictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     * 
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictTypeVO selectDictTypeById(String dictId)
    {
        return DozerUtils.copyProperties(dictTypeMapper.selectById(dictId), SysDictTypeVO.class);
    }

    /**
     * 根据字典类型查询信息
     * 
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictTypeVO selectDictTypeByType(String dictType)
    {
        Optional<SysDictType> sysDictType = dictTypeMapper.selectList(Wrappers.query(SysDictType.builder().dictType(dictType).build())).stream().findFirst();
        if (!sysDictType.isPresent()){
            return null;
        }
        return DozerUtils.copyProperties(sysDictType.get(), SysDictTypeVO.class);
    }

    /**
     * 批量删除字典类型
     * 
     * @param ids 需要删除的数据
     * @return 结果
     */
    @Override
    public int deleteDictTypeByIds(String ids)
    {
        String[] dictIds = Convert.toStrArray(ids);
        for (String dictId : dictIds)
        {
            SysDictTypeVO dictType = selectDictTypeById(dictId);
            if (dictDataMapper.selectCount(Wrappers.query(SysDictData.builder().dictType(dictType.getDictType()).build())) > 0)
            {
                throw new BusinessException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
        }
        int count = dictTypeMapper.deleteBatchIds(Arrays.asList(dictIds));
        if (count > 0)
        {
            DictUtils.clearDictCache();
        }
        return count;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 新增保存字典类型信息
     * 
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictTypeDTO dictType)
    {
        int row = dictTypeMapper.insert(DozerUtils.copyProperties(dictType, SysDictType.class));
        if (row > 0)
        {
            DictUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     * 
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictTypeDTO dictType)
    {
        SysDictType oldDict = dictTypeMapper.selectById(dictType.getId());
        dictDataMapper.update(SysDictData.builder().dictType(dictType.getDictType()).build(),
                Wrappers.query(SysDictData.builder().dictType(oldDict.getDictType()).build()));
        int row = dictTypeMapper.updateById(DozerUtils.copyProperties(dictType, SysDictType.class));
        if (row > 0)
        {
            DictUtils.clearDictCache();
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     * 
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictTypeDTO dict)
    {
        String dictId = StringUtils.isIdNull(dict.getId());
        Optional<SysDictType> dictType = dictTypeMapper.selectList(
                Wrappers.query(SysDictType.builder().dictType(dict.getDictType()).build())).stream().findFirst();
        if (dictType.isPresent() && !dictId.equals(dictType.get().getId()))
        {
            return UserConstants.DICT_TYPE_NOT_UNIQUE;
        }
        return UserConstants.DICT_TYPE_UNIQUE;
    }

    /**
     * 查询字典类型树
     * 
     * @param dictType 字典类型
     * @return 所有字典类型
     */
    @Override
    public List<Ztree> selectDictTree(SysDictTypeDTO dictType)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDictTypeVO> dictList = dictTypeMapper.selectDictTypeList(dictType);
        for (SysDictTypeVO dict : dictList)
        {
            if (UserConstants.DICT_NORMAL.equals(dict.getStatus()))
            {
                ztrees.add(Ztree.builder()
                        .id(dict.getId())
                        .name(transDictName(dict))
                        .title(dict.getDictType())
                        .build());
            }
        }
        return ztrees;
    }

    public String transDictName(SysDictTypeVO dictType)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("(" + dictType.getDictName() + ")");
        sb.append("&nbsp;&nbsp;&nbsp;" + dictType.getDictType());
        return sb.toString();
    }
}
